package com.chuhe.lottery.config;

import com.chuhe.lottery.exception.MyThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
    /**
     * 项目共用线程池
     */
    public static final String LOTTERY_EXECUTOR = "LotteryExecutor";

    @Override
    public Executor getAsyncExecutor() {
        return LotteryExecutor();
    }

    @Bean(LOTTERY_EXECUTOR)
    @Primary
    public ThreadPoolTaskExecutor LotteryExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setWaitForTasksToCompleteOnShutdown(true);//线程池优雅停机的关键开启
        executor.setCorePoolSize(1000);//核心线程数
        executor.setMaxPoolSize(1000);//最大线程数
        executor.setQueueCapacity(2000);//有界队列，避免资源耗尽
        executor.setThreadNamePrefix("lottery-executor-");//线程名称
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//满了调用线程执行，认为重要任务
        executor.setThreadFactory(new MyThreadFactory(executor));//装饰器模式，拦截异常
        executor.initialize();
        return executor;
    }

}